<template>
  <div class="markdown-editor" :class="{ fullscreen: isFullscreen }">
    <!-- 工具栏 -->
    <div class="editor-toolbar" v-if="!readonly">
      <div class="toolbar-group">
        <el-button-group size="small">
          <el-button @click="insertMarkdown('**', '**')" title="粗体 (Ctrl+B)">
            <el-icon><strong>B</strong></el-icon>
          </el-button>
          <el-button @click="insertMarkdown('*', '*')" title="斜体 (Ctrl+I)">
            <el-icon><em>I</em></el-icon>
          </el-button>
          <el-button @click="insertMarkdown('~~', '~~')" title="删除线">
            <el-icon><s>S</s></el-icon>
          </el-button>
          <el-button @click="insertMarkdown('`', '`')" title="行内代码">
            <el-icon><Document /></el-icon>
          </el-button>
        </el-button-group>
      </div>

      <div class="toolbar-group">
        <el-button-group size="small">
          <el-button @click="insertHeader(1)" title="标题 1">H1</el-button>
          <el-button @click="insertHeader(2)" title="标题 2">H2</el-button>
          <el-button @click="insertHeader(3)" title="标题 3">H3</el-button>
          <el-button @click="insertHeader(4)" title="标题 4">H4</el-button>
          <el-button @click="insertHeader(5)" title="标题 5">H5</el-button>
          <el-button @click="insertHeader(6)" title="标题 6">H6</el-button>
        </el-button-group>
      </div>

      <div class="toolbar-group">
        <el-button-group size="small">
          <el-button @click="insertList('- ')" title="无序列表">
            <el-icon><Operation /></el-icon>
          </el-button>
          <el-button @click="insertList('1. ')" title="有序列表">
            <el-icon><List /></el-icon>
          </el-button>
          <el-button @click="insertList('- [ ] ')" title="任务列表">
            <el-icon><Select /></el-icon>
          </el-button>
          <el-button @click="insertQuote()" title="引用">
            <el-icon><ChatDotRound /></el-icon>
          </el-button>
        </el-button-group>
      </div>

      <div class="toolbar-group">
        <el-button-group size="small">
          <el-button @click="insertLink()" title="插入链接">
            <el-icon><Link /></el-icon>
          </el-button>
          <el-button @click="insertImage()" title="插入图片">
            <el-icon><Picture /></el-icon>
          </el-button>
          <el-button @click="insertTable()" title="插入表格">
            <el-icon><Grid /></el-icon>
          </el-button>
          <el-button @click="insertCodeBlock()" title="代码块">
            <el-icon><DocumentCopy /></el-icon>
          </el-button>
        </el-button-group>
      </div>

      <div class="toolbar-group">
        <el-button-group size="small">
          <el-button @click="insertFormula()" title="数学公式">
            <el-icon><Calculator /></el-icon>
          </el-button>
          <el-button @click="insertMermaid()" title="流程图">
            <el-icon><Share /></el-icon>
          </el-button>
          <el-button @click="insertDivider()" title="分割线">
            <el-icon><Minus /></el-icon>
          </el-button>
        </el-button-group>
      </div>

      <div class="toolbar-group">
        <el-button-group size="small">
          <el-button @click="undo()" :disabled="!canUndo" title="撤销 (Ctrl+Z)">
            <el-icon><RefreshLeft /></el-icon>
          </el-button>
          <el-button @click="redo()" :disabled="!canRedo" title="重做 (Ctrl+Y)">
            <el-icon><RefreshRight /></el-icon>
          </el-button>
        </el-button-group>
      </div>

      <div class="toolbar-group">
        <el-button-group size="small">
          <el-button @click="togglePreview()" :type="showPreview ? 'primary' : 'default'" title="预览">
            <el-icon><View /></el-icon>
          </el-button>
          <el-button @click="toggleSyncScroll()" :type="syncScroll ? 'primary' : 'default'" title="同步滚动">
            <el-icon><Connection /></el-icon>
          </el-button>
          <el-button @click="toggleFullscreen()" title="全屏">
            <el-icon><FullScreen /></el-icon>
          </el-button>
        </el-button-group>
      </div>

      <div class="toolbar-group">
        <el-dropdown @command="handleCommand">
          <el-button size="small">
            更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="export-html">导出HTML</el-dropdown-item>
              <el-dropdown-item command="export-pdf">导出PDF</el-dropdown-item>
              <el-dropdown-item command="import-file">导入文件</el-dropdown-item>
              <el-dropdown-item command="word-count">字数统计</el-dropdown-item>
              <el-dropdown-item command="find-replace">查找替换</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 编辑器主体 -->
    <div class="editor-main" :class="{ 'show-preview': showPreview }">
      <!-- 编辑区域 -->
      <div class="editor-pane" v-show="!showPreview || !isMobile">
        <textarea
          ref="editorRef"
          v-model="content"
          class="editor-content"
          :placeholder="placeholder"
          :readonly="readonly"
          @input="handleInput"
          @focus="handleFocus"
          @blur="handleBlur"
          @scroll="handleEditorScroll"
        ></textarea>
      </div>

      <!-- 预览区域 -->
      <div class="preview-pane" v-show="showPreview">
        <div 
          ref="previewRef" 
          class="preview-content" 
          v-html="renderedContent"
          @scroll="handlePreviewScroll"
        ></div>
      </div>
    </div>

    <!-- 状态栏 -->
    <div class="editor-footer" v-if="showStatusBar">
      <div class="status-left">
        <span>行: {{ cursorPosition.line }}</span>
        <span>列: {{ cursorPosition.column }}</span>
        <span>选中: {{ selectedText.length }}</span>
      </div>
      <div class="status-right">
        <span>字符: {{ wordCount.characters }}</span>
        <span>单词: {{ wordCount.words }}</span>
        <span>段落: {{ wordCount.paragraphs }}</span>
        <span>{{ editorMode }}</span>
      </div>
    </div>

    <!-- 链接插入对话框 -->
    <el-dialog v-model="linkDialogVisible" title="插入链接" width="500px">
      <el-form :model="linkForm" label-width="80px">
        <el-form-item label="链接文本">
          <el-input v-model="linkForm.text" placeholder="请输入链接文本" />
        </el-form-item>
        <el-form-item label="链接地址">
          <el-input v-model="linkForm.url" placeholder="请输入链接地址" />
        </el-form-item>
        <el-form-item label="链接标题">
          <el-input v-model="linkForm.title" placeholder="请输入链接标题（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="linkDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmInsertLink">确定</el-button>
      </template>
    </el-dialog>

    <!-- 图片插入对话框 -->
    <el-dialog v-model="imageDialogVisible" title="插入图片" width="600px">
      <el-tabs v-model="imageTabActive">
        <el-tab-pane label="上传图片" name="upload">
          <el-upload
            ref="uploadRef"
            class="image-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
            :on-success="handleImageUploadSuccess"
            :on-error="handleImageUploadError"
            drag
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将图片拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持 jpg/png/gif 文件，且不超过 10MB
              </div>
            </template>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane label="网络图片" name="url">
          <el-form :model="imageForm" label-width="80px">
            <el-form-item label="图片地址">
              <el-input v-model="imageForm.url" placeholder="请输入图片地址" />
            </el-form-item>
            <el-form-item label="替代文本">
              <el-input v-model="imageForm.alt" placeholder="请输入图片描述" />
            </el-form-item>
            <el-form-item label="图片标题">
              <el-input v-model="imageForm.title" placeholder="请输入图片标题（可选）" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <el-button @click="imageDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmInsertImage">确定</el-button>
      </template>
    </el-dialog>

    <!-- 表格插入对话框 -->
    <el-dialog v-model="tableDialogVisible" title="插入表格" width="400px">
      <el-form :model="tableForm" label-width="80px">
        <el-form-item label="行数">
          <el-input-number v-model="tableForm.rows" :min="1" :max="20" />
        </el-form-item>
        <el-form-item label="列数">
          <el-input-number v-model="tableForm.cols" :min="1" :max="10" />
        </el-form-item>
        <el-form-item label="表头">
          <el-switch v-model="tableForm.header" />
        </el-form-item>
        <el-form-item label="对齐方式">
          <el-select v-model="tableForm.align" style="width: 100%">
            <el-option label="左对齐" value="left" />
            <el-option label="居中对齐" value="center" />
            <el-option label="右对齐" value="right" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="tableDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmInsertTable">确定</el-button>
      </template>
    </el-dialog>

    <!-- 代码块插入对话框 -->
    <el-dialog v-model="codeDialogVisible" title="插入代码块" width="600px">
      <el-form :model="codeForm" label-width="80px">
        <el-form-item label="编程语言">
          <el-select v-model="codeForm.language" style="width: 100%" filterable>
            <el-option v-for="lang in codeLanguages" :key="lang.value" :label="lang.label" :value="lang.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="代码内容">
          <el-input
            v-model="codeForm.code"
            type="textarea"
            :rows="10"
            placeholder="请输入代码内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="codeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmInsertCodeBlock">确定</el-button>
      </template>
    </el-dialog>

    <!-- 查找替换对话框 -->
    <el-dialog v-model="findReplaceVisible" title="查找替换" width="500px">
      <el-form :model="findReplaceForm" label-width="80px">
        <el-form-item label="查找">
          <el-input v-model="findReplaceForm.find" placeholder="请输入要查找的内容" />
        </el-form-item>
        <el-form-item label="替换">
          <el-input v-model="findReplaceForm.replace" placeholder="请输入替换内容" />
        </el-form-item>
        <el-form-item label="选项">
          <el-checkbox-group v-model="findReplaceForm.options">
            <el-checkbox label="caseSensitive">区分大小写</el-checkbox>
            <el-checkbox label="wholeWord">全词匹配</el-checkbox>
            <el-checkbox label="regex">正则表达式</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="findNext">查找下一个</el-button>
        <el-button @click="replaceNext">替换</el-button>
        <el-button @click="replaceAll" type="primary">全部替换</el-button>
        <el-button @click="findReplaceVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 字数统计对话框 -->
    <el-dialog v-model="wordCountVisible" title="字数统计" width="400px">
      <div class="word-count-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="字符数">{{ wordCount.characters }}</el-descriptions-item>
          <el-descriptions-item label="字符数(不含空格)">{{ wordCount.charactersNoSpaces }}</el-descriptions-item>
          <el-descriptions-item label="单词数">{{ wordCount.words }}</el-descriptions-item>
          <el-descriptions-item label="段落数">{{ wordCount.paragraphs }}</el-descriptions-item>
          <el-descriptions-item label="行数">{{ wordCount.lines }}</el-descriptions-item>
          <el-descriptions-item label="阅读时间">{{ readingTime }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="wordCountVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// Props定义
interface Props {
  modelValue?: string
  placeholder?: string
  readonly?: boolean
  height?: string | number
  showStatusBar?: boolean
  showPreview?: boolean
  syncScroll?: boolean
  theme?: 'light' | 'dark' | 'auto'
  editorMode?: 'normal' | 'vim'
  uploadUrl?: string
  uploadHeaders?: Record<string, string>
  maxLength?: number
  autoSave?: boolean
  autoSaveInterval?: number
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  placeholder: '请输入Markdown内容...',
  readonly: false,
  height: '500px',
  showStatusBar: true,
  showPreview: true,
  syncScroll: true,
  theme: 'auto',
  editorMode: 'normal',
  uploadUrl: '/api/upload/image',
  uploadHeaders: () => ({}),
  maxLength: 0,
  autoSave: false,
  autoSaveInterval: 30000
})

// Emits定义
interface Emits {
  (e: 'update:modelValue', value: string): void
  (e: 'change', value: string): void
  (e: 'save', value: string): void
  (e: 'focus'): void
  (e: 'blur'): void
  (e: 'ready'): void
}

const emit = defineEmits<Emits>()

// 响应式数据
const editorRef = ref<HTMLTextAreaElement>()
const previewRef = ref<HTMLElement>()
const uploadRef = ref()
const content = ref(props.modelValue)

// 编辑器状态
const isFullscreen = ref(false)
const showPreview = ref(props.showPreview)
const syncScroll = ref(props.syncScroll)
const canUndo = ref(false)
const canRedo = ref(false)
const isMobile = ref(false)

// 光标位置
const cursorPosition = reactive({
  line: 1,
  column: 1
})

// 选中文本
const selectedText = ref('')

// 对话框状态
const linkDialogVisible = ref(false)
const imageDialogVisible = ref(false)
const tableDialogVisible = ref(false)
const codeDialogVisible = ref(false)
const findReplaceVisible = ref(false)
const wordCountVisible = ref(false)

// 表单数据
const linkForm = reactive({
  text: '',
  url: '',
  title: ''
})

const imageForm = reactive({
  url: '',
  alt: '',
  title: ''
})

const imageTabActive = ref('upload')

const tableForm = reactive({
  rows: 3,
  cols: 3,
  header: true,
  align: 'left'
})

const codeForm = reactive({
  language: 'javascript',
  code: ''
})

const findReplaceForm = reactive({
  find: '',
  replace: '',
  options: [] as string[]
})

// 代码语言选项
const codeLanguages = [
  { label: 'JavaScript', value: 'javascript' },
  { label: 'TypeScript', value: 'typescript' },
  { label: 'HTML', value: 'html' },
  { label: 'CSS', value: 'css' },
  { label: 'Python', value: 'python' },
  { label: 'Java', value: 'java' },
  { label: 'C++', value: 'cpp' },
  { label: 'C#', value: 'csharp' },
  { label: 'PHP', value: 'php' },
  { label: 'Go', value: 'go' },
  { label: 'Rust', value: 'rust' },
  { label: 'SQL', value: 'sql' },
  { label: 'Shell', value: 'bash' },
  { label: 'JSON', value: 'json' },
  { label: 'XML', value: 'xml' },
  { label: 'Markdown', value: 'markdown' },
  { label: 'YAML', value: 'yaml' },
  { label: 'TOML', value: 'toml' },
  { label: 'Dockerfile', value: 'dockerfile' },
  { label: 'Nginx', value: 'nginx' }
]

// 计算属性
const editorMode = computed(() => {
  return props.editorMode === 'vim' ? 'Vim' : 'Normal'
})

const wordCount = computed(() => {
  const text = content.value || ''
  const lines = text.split('\n')
  const charactersNoSpaces = text.replace(/\s/g, '').length

  return {
    characters: text.length,
    charactersNoSpaces,
    words: text.trim() ? text.trim().split(/\s+/).length : 0,
    paragraphs: text.trim() ? text.split(/\n\s*\n/).length : 0,
    lines: lines.length
  }
})

const readingTime = computed(() => {
  const wordsPerMinute = 200
  const minutes = Math.ceil(wordCount.value.words / wordsPerMinute)
  return `约 ${minutes} 分钟`
})

// 简单的Markdown渲染
const renderedContent = computed(() => {
  const text = content.value || ''
  if (!text.trim()) return '<div class="empty-content">暂无内容</div>'

  try {
    // 简单的Markdown转HTML
    let html = text
      // 标题
      .replace(/^### (.*$)/gim, '<h3>$1</h3>')
      .replace(/^## (.*$)/gim, '<h2>$1</h2>')
      .replace(/^# (.*$)/gim, '<h1>$1</h1>')
      // 粗体
      .replace(/\*\*(.*)\*\*/gim, '<strong>$1</strong>')
      // 斜体
      .replace(/\*(.*)\*/gim, '<em>$1</em>')
      // 代码
      .replace(/`(.*?)`/gim, '<code>$1</code>')
      // 链接
      .replace(/\[([^\]]+)\]\(([^)]+)\)/gim, '<a href="$2" target="_blank">$1</a>')
      // 图片
      .replace(/!\[([^\]]*)\]\(([^)]+)\)/gim, '<img src="$2" alt="$1" style="max-width: 100%;">')
      // 换行
      .replace(/\n/gim, '<br>')

    return html
  } catch (error) {
    console.error('Markdown渲染错误:', error)
    return '<div class="render-error">内容渲染失败</div>'
  }
})

// 初始化编辑器
const initEditor = () => {
  if (!editorRef.value) return

  try {
    // 设置编辑器高度
    if (typeof props.height === 'number') {
      editorRef.value.style.height = `${props.height}px`
    } else {
      editorRef.value.style.height = props.height
    }

    emit('ready')
  } catch (error) {
    console.error('编辑器初始化失败:', error)
    ElMessage.error('编辑器初始化失败')
  }
}

// 处理输入
const handleInput = (event: Event) => {
  const target = event.target as HTMLTextAreaElement
  content.value = target.value
  emit('update:modelValue', content.value)
  emit('change', content.value)
  updateCursorPosition()
}

// 处理焦点
const handleFocus = () => {
  emit('focus')
}

// 处理失焦
const handleBlur = () => {
  emit('blur')
}

// 更新光标位置
const updateCursorPosition = () => {
  if (!editorRef.value) return

  const textarea = editorRef.value
  const text = textarea.value
  const selectionStart = textarea.selectionStart

  const lines = text.substring(0, selectionStart).split('\n')
  cursorPosition.line = lines.length
  cursorPosition.column = lines[lines.length - 1].length + 1
}

// 更新撤销重做状态
const updateUndoRedoState = () => {
  // 简化处理
  canUndo.value = true
  canRedo.value = true
}

// 插入Markdown语法
const insertMarkdown = (before: string, after: string = '', placeholder: string = '') => {
  if (!editorRef.value) return

  const textarea = editorRef.value
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  const selectedText = textarea.value.substring(start, end)
  const text = selectedText || placeholder

  const insert = `${before}${text}${after}`

  const newValue = textarea.value.substring(0, start) + insert + textarea.value.substring(end)
  content.value = newValue
  emit('update:modelValue', content.value)
  emit('change', content.value)

  // 设置新的光标位置
  nextTick(() => {
    textarea.focus()
    textarea.setSelectionRange(start + before.length, start + before.length + text.length)
  })
}

// 插入标题
const insertHeader = (level: number) => {
  if (!editorRef.value) return

  const textarea = editorRef.value
  const start = textarea.selectionStart
  const value = textarea.value

  // 找到当前行的开始位置
  const lineStart = value.lastIndexOf('\n', start - 1) + 1
  const lineEnd = value.indexOf('\n', start)
  const currentLine = value.substring(lineStart, lineEnd === -1 ? value.length : lineEnd)

  // 移除现有的标题标记
  const cleanText = currentLine.replace(/^#+\s*/, '')
  const headerPrefix = '#'.repeat(level) + ' '
  const newLine = headerPrefix + cleanText

  const newValue = value.substring(0, lineStart) + newLine + value.substring(lineEnd === -1 ? value.length : lineEnd)
  content.value = newValue
  emit('update:modelValue', content.value)
  emit('change', content.value)

  nextTick(() => {
    textarea.focus()
  })
}

// 插入列表
const insertList = (prefix: string) => {
  if (!editorRef.value) return

  const textarea = editorRef.value
  const start = textarea.selectionStart
  const value = textarea.value

  // 找到当前行的开始位置
  const lineStart = value.lastIndexOf('\n', start - 1) + 1
  const lineEnd = value.indexOf('\n', start)
  const currentLine = value.substring(lineStart, lineEnd === -1 ? value.length : lineEnd)

  let newValue
  if (currentLine.trim() === '') {
    // 空行，直接插入列表项
    newValue = value.substring(0, lineStart) + prefix + value.substring(lineEnd === -1 ? value.length : lineEnd)
  } else {
    // 非空行，在行首插入列表标记
    newValue = value.substring(0, lineStart) + prefix + currentLine + value.substring(lineEnd === -1 ? value.length : lineEnd)
  }

  content.value = newValue
  emit('update:modelValue', content.value)
  emit('change', content.value)

  nextTick(() => {
    textarea.focus()
  })
}

// 插入引用
const insertQuote = () => {
  insertList('> ')
}

// 插入链接
const insertLink = () => {
  if (!editorRef.value) return

  const textarea = editorRef.value
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  const selectedText = textarea.value.substring(start, end)

  linkForm.text = selectedText || ''
  linkForm.url = ''
  linkForm.title = ''
  linkDialogVisible.value = true
}

// 确认插入链接
const confirmInsertLink = () => {
  if (!editorRef.value || !linkForm.url) return

  const textarea = editorRef.value
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  const linkText = linkForm.text || linkForm.url
  const title = linkForm.title ? ` "${linkForm.title}"` : ''
  const markdown = `[${linkText}](${linkForm.url}${title})`

  const newValue = textarea.value.substring(0, start) + markdown + textarea.value.substring(end)
  content.value = newValue
  emit('update:modelValue', content.value)
  emit('change', content.value)

  linkDialogVisible.value = false

  nextTick(() => {
    textarea.focus()
  })
}

// 插入图片
const insertImage = () => {
  imageForm.url = ''
  imageForm.alt = ''
  imageForm.title = ''
  imageTabActive.value = 'upload'
  imageDialogVisible.value = true
}

// 图片上传前验证
const beforeImageUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB!')
    return false
  }
  return true
}

// 图片上传成功
const handleImageUploadSuccess = (response: any) => {
  if (response.code === 0) {
    insertImageMarkdown(response.data.url, '', '')
    imageDialogVisible.value = false
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.msg || '图片上传失败')
  }
}

// 图片上传失败
const handleImageUploadError = () => {
  ElMessage.error('图片上传失败')
}

// 确认插入图片
const confirmInsertImage = () => {
  if (!imageForm.url) {
    ElMessage.warning('请输入图片地址')
    return
  }

  insertImageMarkdown(imageForm.url, imageForm.alt, imageForm.title)
  imageDialogVisible.value = false
}

// 插入图片Markdown
const insertImageMarkdown = (url: string, alt: string, title: string) => {
  if (!editorRef.value) return

  const textarea = editorRef.value
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  const titlePart = title ? ` "${title}"` : ''
  const markdown = `![${alt}](${url}${titlePart})`

  const newValue = textarea.value.substring(0, start) + markdown + textarea.value.substring(end)
  content.value = newValue
  emit('update:modelValue', content.value)
  emit('change', content.value)

  nextTick(() => {
    textarea.focus()
  })
}

// 插入表格
const insertTable = () => {
  tableForm.rows = 3
  tableForm.cols = 3
  tableForm.header = true
  tableForm.align = 'left'
  tableDialogVisible.value = true
}

// 确认插入表格
const confirmInsertTable = () => {
  if (!editorView) return

  const { rows, cols, header, align } = tableForm
  let markdown = '\n'

  // 生成表头
  if (header) {
    markdown += '|'
    for (let i = 0; i < cols; i++) {
      markdown += ` 表头${i + 1} |`
    }
    markdown += '\n|'

    // 生成对齐行
    for (let i = 0; i < cols; i++) {
      switch (align) {
        case 'left':
          markdown += ' :--- |'
          break
        case 'center':
          markdown += ' :---: |'
          break
        case 'right':
          markdown += ' ---: |'
          break
        default:
          markdown += ' --- |'
      }
    }
    markdown += '\n'
  }

  // 生成表格内容
  const startRow = header ? 1 : 0
  for (let i = startRow; i < rows; i++) {
    markdown += '|'
    for (let j = 0; j < cols; j++) {
      markdown += ` 内容${i + 1}-${j + 1} |`
    }
    markdown += '\n'
  }

  markdown += '\n'

  const selection = editorView.state.selection.main
  editorView.dispatch({
    changes: {
      from: selection.from,
      to: selection.to,
      insert: markdown
    }
  })

  tableDialogVisible.value = false
  editorView.focus()
}

// 插入代码块
const insertCodeBlock = () => {
  codeForm.language = 'javascript'
  codeForm.code = ''
  codeDialogVisible.value = true
}

// 确认插入代码块
const confirmInsertCodeBlock = () => {
  if (!editorRef.value) return

  const textarea = editorRef.value
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  const markdown = `\n\`\`\`${codeForm.language}\n${codeForm.code}\n\`\`\`\n`

  const newValue = textarea.value.substring(0, start) + markdown + textarea.value.substring(end)
  content.value = newValue
  emit('update:modelValue', content.value)
  emit('change', content.value)

  codeDialogVisible.value = false

  nextTick(() => {
    textarea.focus()
  })
}

// 插入数学公式
const insertFormula = () => {
  ElMessageBox.prompt('请输入LaTeX公式', '插入数学公式', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPlaceholder: '例如: E = mc^2'
  }).then(({ value }) => {
    if (!editorRef.value || !value) return

    insertMarkdown(`$$${value}$$`)
  }).catch(() => {
    // 用户取消
  })
}

// 插入Mermaid图表
const insertMermaid = () => {
  ElMessageBox.prompt('请输入Mermaid图表代码', '插入流程图', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'textarea',
    inputPlaceholder: 'graph TD\n    A[开始] --> B[处理]\n    B --> C[结束]'
  }).then(({ value }) => {
    if (!editorRef.value || !value) return

    insertMarkdown(`\n\`\`\`mermaid\n${value}\n\`\`\`\n`)
  }).catch(() => {
    // 用户取消
  })
}

// 插入分割线
const insertDivider = () => {
  insertMarkdown('\n\n---\n\n')
}

// 撤销
const undo = () => {
  if (!editorRef.value) return
  document.execCommand('undo')
  editorRef.value.focus()
}

// 重做
const redo = () => {
  if (!editorRef.value) return
  document.execCommand('redo')
  editorRef.value.focus()
}

// 切换预览
const togglePreview = () => {
  showPreview.value = !showPreview.value
}

// 切换同步滚动
const toggleSyncScroll = () => {
  syncScroll.value = !syncScroll.value
}

// 切换全屏
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value

  if (isFullscreen.value) {
    document.body.style.overflow = 'hidden'
  } else {
    document.body.style.overflow = ''
  }
}

// 处理编辑器滚动
const handleEditorScroll = () => {
  if (!syncScroll.value || !editorRef.value || !previewRef.value) return

  const editorScrollTop = editorRef.value.scrollTop
  const editorScrollHeight = editorRef.value.scrollHeight - editorRef.value.clientHeight
  const scrollRatio = editorScrollHeight > 0 ? editorScrollTop / editorScrollHeight : 0

  const previewScrollHeight = previewRef.value.scrollHeight - previewRef.value.clientHeight
  const previewScrollTop = scrollRatio * previewScrollHeight

  previewRef.value.scrollTop = previewScrollTop
}

// 处理预览滚动
const handlePreviewScroll = () => {
  if (!syncScroll.value || !editorRef.value || !previewRef.value) return

  const previewScrollTop = previewRef.value.scrollTop
  const previewScrollHeight = previewRef.value.scrollHeight - previewRef.value.clientHeight
  const scrollRatio = previewScrollHeight > 0 ? previewScrollTop / previewScrollHeight : 0

  const editorScrollHeight = editorRef.value.scrollHeight - editorRef.value.clientHeight
  const editorScrollTop = scrollRatio * editorScrollHeight

  editorRef.value.scrollTop = editorScrollTop
}

// 处理命令
const handleCommand = (command: string) => {
  switch (command) {
    case 'export-html':
      exportHTML()
      break
    case 'export-pdf':
      exportPDF()
      break
    case 'import-file':
      importFile()
      break
    case 'word-count':
      wordCountVisible.value = true
      break
    case 'find-replace':
      findReplaceVisible.value = true
      break
  }
}

// 导出HTML
const exportHTML = () => {
  const html = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Markdown Export</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/styles/github.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.16.8/katex.min.css">
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; max-width: 800px; margin: 0 auto; padding: 20px; }
        .markdown-table { border-collapse: collapse; width: 100%; margin: 16px 0; }
        .markdown-table th, .markdown-table td { border: 1px solid #dfe2e5; padding: 8px 12px; text-align: left; }
        .markdown-table th { background: #f6f8fa; font-weight: 600; }
        img { max-width: 100%; height: auto; }
        pre { background: #f6f8fa; padding: 16px; border-radius: 6px; overflow-x: auto; }
        blockquote { border-left: 4px solid #dfe2e5; margin: 16px 0; padding: 0 16px; color: #6a737d; }
    </style>
</head>
<body>
${renderedContent.value}
</body>
</html>`

  const blob = new Blob([html], { type: 'text/html' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = 'markdown-export.html'
  a.click()
  URL.revokeObjectURL(url)

  ElMessage.success('HTML导出成功')
}

// 导出PDF
const exportPDF = () => {
  ElMessage.info('PDF导出功能需要服务端支持')
}

// 导入文件
const importFile = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.md,.txt'
  input.onchange = (e) => {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (!file) return

    const reader = new FileReader()
    reader.onload = (e) => {
      const content = e.target?.result as string
      if (editorView) {
        editorView.dispatch({
          changes: {
            from: 0,
            to: editorView.state.doc.length,
            insert: content
          }
        })
        ElMessage.success('文件导入成功')
      }
    }
    reader.readAsText(file)
  }
  input.click()
}

// 查找下一个
const findNext = () => {
  if (!editorView || !findReplaceForm.find) return

  // 实现查找逻辑
  ElMessage.info('查找功能开发中')
}

// 替换下一个
const replaceNext = () => {
  if (!editorView || !findReplaceForm.find) return

  // 实现替换逻辑
  ElMessage.info('替换功能开发中')
}

// 全部替换
const replaceAll = () => {
  if (!editorView || !findReplaceForm.find) return

  // 实现全部替换逻辑
  ElMessage.info('全部替换功能开发中')
}

// 获取内容
const getContent = () => {
  return content.value
}

// 设置内容
const setContent = (newContent: string) => {
  content.value = newContent
  emit('update:modelValue', content.value)
}

// 获取选中文本
const getSelectedText = () => {
  if (!editorRef.value) return ''
  const textarea = editorRef.value
  return textarea.value.substring(textarea.selectionStart, textarea.selectionEnd)
}

// 插入文本
const insertText = (text: string) => {
  if (!editorRef.value) return

  const textarea = editorRef.value
  const start = textarea.selectionStart
  const end = textarea.selectionEnd

  const newValue = textarea.value.substring(0, start) + text + textarea.value.substring(end)
  content.value = newValue
  emit('update:modelValue', content.value)
  emit('change', content.value)

  nextTick(() => {
    textarea.focus()
    textarea.setSelectionRange(start + text.length, start + text.length)
  })
}

// 聚焦编辑器
const focus = () => {
  if (!editorRef.value) return
  editorRef.value.focus()
}

// 失焦编辑器
const blur = () => {
  if (!editorRef.value) return
  editorRef.value.blur()
}

// 检测移动设备
const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768
}

// 监听props变化
watch(() => props.modelValue, (newValue) => {
  if (newValue !== content.value) {
    content.value = newValue || ''
  }
})

// 生命周期
onMounted(() => {
  checkMobile()
  window.addEventListener('resize', checkMobile)

  nextTick(() => {
    initEditor()
  })
})

onBeforeUnmount(() => {
  if (isFullscreen.value) {
    document.body.style.overflow = ''
  }

  window.removeEventListener('resize', checkMobile)
})

// 暴露方法给父组件
defineExpose({
  getContent,
  setContent,
  getSelectedText,
  insertText,
  insertMarkdown,
  insertHeader,
  insertList,
  insertQuote,
  insertLink: confirmInsertLink,
  insertImage: insertImageMarkdown,
  insertTable: confirmInsertTable,
  insertCodeBlock: confirmInsertCodeBlock,
  insertFormula,
  insertMermaid,
  insertDivider,
  focus,
  blur,
  undo,
  redo,
  togglePreview,
  toggleFullscreen,
  exportHTML,
  exportPDF,
  importFile
})
</script>

<style lang="scss" scoped>
.markdown-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: #fff;
  display: flex;
  flex-direction: column;

  &.fullscreen {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 9999;
    background: #fff;
  }

  .editor-toolbar {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 8px;
    padding: 12px;
    border-bottom: 1px solid #e4e7ed;
    background: #f8f9fa;

    .toolbar-group {
      display: flex;
      align-items: center;
      gap: 4px;

      .el-button {
        &.active {
          background: #409eff;
          color: #fff;
          border-color: #409eff;
        }
      }
    }
  }

  .editor-main {
    flex: 1;
    display: flex;
    min-height: 500px;

    &.show-preview {
      .editor-pane {
        border-right: 1px solid #e4e7ed;
      }
    }

    .editor-pane {
      flex: 1;
      position: relative;

      .editor-content {
        width: 100%;
        height: 100%;
        border: none;
        outline: none;
        resize: none;
        padding: 16px;
        font-family: 'JetBrains Mono', 'Fira Code', 'Source Code Pro', Consolas, monospace;
        font-size: 14px;
        line-height: 1.6;
        background: transparent;
        color: inherit;

        &::placeholder {
          color: #c0c4cc;
        }

        &:focus {
          outline: none;
        }
      }
    }

    .preview-pane {
      flex: 1;
      background: #fff;
      overflow-y: auto;
      padding: 20px;

      .preview-content {
        font-size: 14px;
        line-height: 1.6;
        color: #24292f;

        // 标题样式
        h1, h2, h3, h4, h5, h6 {
          margin: 24px 0 16px 0;
          font-weight: 600;
          line-height: 1.25;
          color: #24292f;
        }

        h1 {
          font-size: 2em;
          border-bottom: 1px solid #d0d7de;
          padding-bottom: 10px;
        }

        h2 {
          font-size: 1.5em;
          border-bottom: 1px solid #d0d7de;
          padding-bottom: 8px;
        }

        h3 {
          font-size: 1.25em;
        }

        h4 {
          font-size: 1em;
        }

        h5 {
          font-size: 0.875em;
        }

        h6 {
          font-size: 0.85em;
          color: #656d76;
        }

        // 段落样式
        p {
          margin: 16px 0;
        }

        // 链接样式
        a {
          color: #0969da;
          text-decoration: none;

          &:hover {
            text-decoration: underline;
          }
        }

        // 列表样式
        ul, ol {
          margin: 16px 0;
          padding-left: 32px;

          li {
            margin: 4px 0;

            p {
              margin: 8px 0;
            }
          }
        }

        // 引用样式
        blockquote {
          margin: 16px 0;
          padding: 0 16px;
          color: #656d76;
          border-left: 4px solid #d0d7de;

          p {
            margin: 8px 0;
          }
        }

        // 代码样式
        code {
          background-color: rgba(175, 184, 193, 0.2);
          border-radius: 3px;
          padding: 2px 4px;
          font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
          font-size: 85%;
        }

        pre {
          background-color: #f6f8fa;
          border-radius: 6px;
          padding: 16px;
          overflow-x: auto;
          margin: 16px 0;

          code {
            background: transparent;
            padding: 0;
            border-radius: 0;
            font-size: 85%;
          }
        }

        // 表格样式
        .table-wrapper {
          overflow-x: auto;
          margin: 16px 0;
        }

        .markdown-table {
          border-collapse: collapse;
          width: 100%;
          border-spacing: 0;

          th, td {
            border: 1px solid #d0d7de;
            padding: 8px 12px;
            text-align: left;
          }

          th {
            background-color: #f6f8fa;
            font-weight: 600;
          }

          tr:nth-child(even) {
            background-color: #f6f8fa;
          }
        }

        // 图片样式
        img {
          max-width: 100%;
          height: auto;
          border-radius: 6px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          margin: 16px 0;
        }

        // 分割线样式
        hr {
          border: none;
          border-top: 1px solid #d0d7de;
          margin: 24px 0;
        }

        // 数学公式样式
        .katex {
          font-size: 1.1em;
        }

        .katex-display {
          margin: 16px 0;
          text-align: center;
        }

        // Mermaid图表样式
        .mermaid-diagram {
          text-align: center;
          margin: 16px 0;

          svg {
            max-width: 100%;
            height: auto;
          }
        }

        .mermaid-error {
          color: #d1242f;
          background-color: #fff1f3;
          border: 1px solid #ffb3ba;
          border-radius: 6px;
          padding: 16px;
          margin: 16px 0;
        }

        // 数学公式错误样式
        .math-error {
          color: #d1242f;
          background-color: #fff1f3;
          border-radius: 3px;
          padding: 2px 4px;
        }

        // 空内容样式
        .empty-content {
          text-align: center;
          color: #656d76;
          font-style: italic;
          padding: 40px 20px;
        }

        // 渲染错误样式
        .render-error {
          color: #d1242f;
          background-color: #fff1f3;
          border: 1px solid #ffb3ba;
          border-radius: 6px;
          padding: 16px;
          margin: 16px 0;
          text-align: center;
        }
      }
    }
  }

  .editor-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 12px;
    border-top: 1px solid #e4e7ed;
    background: #f8f9fa;
    font-size: 12px;
    color: #909399;

    .status-left, .status-right {
      display: flex;
      gap: 16px;
    }
  }
}

// 对话框样式
.image-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;

    &:hover {
      border-color: #409eff;
    }
  }

  :deep(.el-upload-dragger) {
    background-color: #fff;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    box-sizing: border-box;
    width: 100%;
    height: 180px;
    text-align: center;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;

    &:hover {
      border-color: #409eff;
    }

    .el-icon--upload {
      font-size: 67px;
      color: #c0c4cc;
      margin: 40px 0 16px;
      line-height: 50px;
    }

    .el-upload__text {
      color: #606266;
      font-size: 14px;
      text-align: center;

      em {
        color: #409eff;
        font-style: normal;
      }
    }
  }
}

.word-count-detail {
  .el-descriptions {
    margin: 16px 0;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .markdown-editor {
    .editor-toolbar {
      padding: 8px;
      gap: 4px;

      .toolbar-group {
        gap: 2px;
      }

      .el-button {
        padding: 4px 8px;
        font-size: 12px;
      }
    }

    .editor-main {
      flex-direction: column;

      &.show-preview {
        .editor-pane {
          border-right: none;
          border-bottom: 1px solid #e4e7ed;
          max-height: 300px;
        }
      }

      .preview-pane {
        padding: 12px;
      }
    }

    .editor-footer {
      flex-direction: column;
      gap: 8px;
      align-items: flex-start;

      .status-left, .status-right {
        gap: 8px;
      }
    }
  }
}

// 暗色主题支持
@media (prefers-color-scheme: dark) {
  .markdown-editor {
    border-color: #4c4d4f;
    background: #1d1e1f;

    .editor-toolbar {
      background: #2d2e2f;
      border-color: #4c4d4f;
    }

    .editor-main {
      .editor-pane {
        border-color: #4c4d4f;
      }

      .preview-pane {
        background: #1d1e1f;

        .preview-content {
          color: #e4e6ea;

          h1, h2, h3, h4, h5, h6 {
            color: #e4e6ea;
            border-color: #4c4d4f;
          }

          h6 {
            color: #8a8b8c;
          }

          a {
            color: #58a6ff;
          }

          blockquote {
            color: #8a8b8c;
            border-color: #4c4d4f;
          }

          code {
            background-color: rgba(110, 118, 129, 0.4);
          }

          pre {
            background-color: #2d2e2f;
          }

          .markdown-table {
            th, td {
              border-color: #4c4d4f;
            }

            th {
              background-color: #2d2e2f;
            }

            tr:nth-child(even) {
              background-color: #2d2e2f;
            }
          }

          hr {
            border-color: #4c4d4f;
          }
        }
      }
    }

    .editor-footer {
      background: #2d2e2f;
      border-color: #4c4d4f;
      color: #8a8b8c;
    }
  }
}
</style>
